package com.lx.idgenerator.segement.bus;

import com.google.common.eventbus.Subscribe;
import com.lx.idgenerator.exception.BizException;
import com.lx.idgenerator.segement.Segment;
import com.lx.idgenerator.segement.SegmentBuffer;
import com.lx.idgenerator.segement.leaf.ILeafInfoService;
import com.lx.idgenerator.segement.leaf.LeafInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lX
 * @version JDK 8
 * @className FillSegmentListener (此处以class为例)
 * @date 2024/10/28
 * @description 填充分段缓存监听器
 */

public class FillSegmentListener {

    Logger logger = LoggerFactory.getLogger(FillSegmentListener.class);


    @Subscribe
    private void fillSegmentCache(FillSegmentEvent event) {

        logger.info("FillSegmentListener接收到的事件:{}", event);
        /**
         * 分段缓存buffer
         */
        SegmentBuffer segmentBuffer = event.getSegmentBuffer();
        //leaf节点服务
        ILeafInfoService leafInfoService = event.getLeafInfoService();
        //业务key
        String tag = event.getTag();

        if(null == segmentBuffer){
            throw new BizException("分段缓存对象为空,请检查");
        }

        if(null == leafInfoService){
            throw new BizException("leaf节点服务为空,请检查");

        }

        if(null == tag){
            throw new BizException("业务Tag为空,请检查");
        }


        Segment segment = null;
        Throwable e = null;

        try {
            LeafInfo leafInfo = leafInfoService.getLeafInfo(tag);
            logger.info("leafInfo服务获取leafInfo,结果:{}",leafInfo);
            segment = leafInfoToSegment(leafInfo);

        }catch (Exception exception){
            e = exception;
        }

        //填充
        segmentBuffer.setChangeSegment(segment);
        // 设置发生异常   扩容异常回调
        segmentBuffer.fillComplete(e);


    }

    /**
     * leaf信息转换为分段缓存对象
     * @param leafInfo
     * @return
     */
    private Segment leafInfoToSegment(LeafInfo leafInfo){
        if(null == leafInfo){
            throw new BizException("获取leafInfo节点信息为空,请检查数据源数据");
        }

        Segment segment = new Segment();
        long curId = leafInfo.getCurId();
        curId = curId ==0 ? 1l : curId;
        segment.setCurId(curId);
        segment.setMinId(curId);
        segment.setMaxId(leafInfo.getMaxId());
        return segment;


    }


}
